package com.product.controller;

import com.product.enmu.HttpStatusEnum;
import com.product.entity.Users;
import com.product.handler.ParameterValidationException;
import com.product.result.ApiResult;
import com.product.service.IUsersService;
import com.product.to.AddUserTo;
import com.product.to.LoginUserTo;
import com.product.to.UpdateUserTo;
import com.product.utils.JwtUtil;
import com.product.utils.PageUtils;
import com.product.utils.ThreadLocalUtils;
import com.product.vo.UserVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;


@Tag(name = "用户控制器")
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private IUsersService usersService;
    @Autowired
    private JwtUtil jwtUtil;

    @Parameters({
            @Parameter(name = "size", description = "每页条数，默认10条"),
            @Parameter(name = "current", description = "分页页数，默认第一页"),
            @Parameter(name = "username", description = "用户名模糊查询"),
            @Parameter(name = "token", description = "用户token,放到请求头的Authorization属性")
    })
    @Operation(summary = "获取所有用户")
    @GetMapping("/all")
    private ApiResult<PageUtils> getAllUsers(@RequestParam(name = "size", defaultValue = "10") Integer size,
                                             @RequestParam(name = "current", defaultValue = "1") Integer current,
                                             @RequestParam(name = "username", required = false) String username) {
        return ApiResult.ok(usersService.getAllUser(size, current, username));
    }

    @Parameter(name = "token", description = "用户token,放到请求头的Authorization属性")
    @Operation(summary = "添加用户")
    @PostMapping("/add")
    private ApiResult<Boolean> addUsers(@Valid @RequestBody AddUserTo user, BindingResult result) throws ParameterValidationException {
        if (result.hasErrors()) {
            StringBuilder errors = new StringBuilder();
            result.getAllErrors().forEach(error -> errors.append(error.getDefaultMessage()).append("\n"));
            throw new ParameterValidationException(errors.toString(), HttpStatusEnum.PARAM_ERROR.getCode());
        }
        if (usersService.getUserByUsername(user.getUsername()) != null) {
            return ApiResult.getResult(null, HttpStatusEnum.ERROR.getCode(), "该用户名已经被使用");
        }
        usersService.addUser(user);
        return ApiResult.ok();
    }

    @Parameter(name = "token", description = "用户token,放到请求头的Authorization属性")
    @Operation(summary = "修改用户")
    @PostMapping("/update")
    private ApiResult<Boolean> updateUser(@Valid @RequestBody UpdateUserTo user, BindingResult result) throws ParameterValidationException {
        if (result.hasErrors()) {
            StringBuilder errors = new StringBuilder();
            result.getAllErrors().forEach(error -> errors.append(error.getDefaultMessage()).append("\n"));
            throw new ParameterValidationException(errors.toString(), HttpStatusEnum.PARAM_ERROR.getCode());
        }
        Users byUsername = usersService.getUserByUsername(user.getUsername());
        if (byUsername != null && !Objects.equals(user.getUserId(), byUsername.getUserId())) {
            return ApiResult.getResult(null, HttpStatusEnum.ERROR.getCode(), "该用户名已经被使用");
        }
        if (user.getPassword() != null && !user.getPassword().isBlank() && (user.getPassword().length() < 6 || user.getPassword().length() > 16)) {
            return ApiResult.getResult(null, HttpStatusEnum.ERROR.getCode(), "密码长度应该为6-16位");
        }
        usersService.updateUser(user);
        return ApiResult.ok();
    }

    @Parameters({
            @Parameter(name = "userId", description = "用户id"),
            @Parameter(name = "token", description = "用户token,放到请求头的Authorization属性")
    })
    @Operation(summary = "删除用户")
    @PostMapping("/delete")
    private ApiResult<Boolean> deleteUser(@RequestParam(name = "userId") Integer userId) {
        usersService.deleteUser(userId);
        return ApiResult.ok();
    }

    @Parameter(name = "token", description = "用户token,放到请求头的Authorization属性")
    @Operation(summary = "批量删除用户")
    @PostMapping("/deletes")
    private ApiResult<Boolean> deleteUsers(@RequestBody List<Integer> userIds) {
        usersService.deleteUsers(userIds);
        return ApiResult.ok();
    }


    @Operation(summary = "登录")
    @PostMapping("/login")
    private ApiResult<String> login(@Valid @RequestBody LoginUserTo user, BindingResult result) throws ParameterValidationException {
        if (result.hasErrors()) {
            StringBuilder errors = new StringBuilder();
            result.getAllErrors().forEach(error -> errors.append(error.getDefaultMessage()).append("\n"));
            throw new ParameterValidationException(errors.toString(), HttpStatusEnum.PARAM_ERROR.getCode());
        }
        Users checkUser = usersService.getUserByUsername(user.getUsername());
        //如果密码正确
        if (checkUser != null && checkUser.getPassword().equals(user.getPassword())) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(checkUser, userVo);
            String token = jwtUtil.createToken(userVo);
            return ApiResult.ok(token, "登录成功");
        } else {
            return ApiResult.getResult(null, HttpStatusEnum.ERROR.getCode(), "用户名或密码错误");
        }
    }

    @Operation(summary = "获取当前登录用户")
    @GetMapping("/getCurrUser")
    private ApiResult<UserVo> getCurrUser() {
        UserVo userVo = ThreadLocalUtils.get();
        return ApiResult.ok(userVo);
    }
}
